package com.mathassistant.server.domain;

import java.util.ArrayList;

import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.jdo.listener.StoreCallback;

import com.mathassistant.shared.TheoryDTO;

@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class Theory implements StoreCallback{
	@PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    @Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
    private String key;

	@Persistent
	private String titleLesson;
	
	@Persistent(serialized = "true")
	private
	ArrayList<String> contentLesson = new ArrayList<String>();
	
	@Persistent
	private Topic topicTheory;
	
	
	public Theory(){}
	public Theory(String titleLesson, String contentLesson){
		this.setTitleLesson(titleLesson);
		this.setContentLesson(convertString2ArrayList(contentLesson));
	}
	public Theory(TheoryDTO lesson){
		this.setTitleLesson(lesson.getTitleLesson());
		this.setContentLesson(convertString2ArrayList(lesson.getContentLesson()));
	}
	
	
	public TheoryDTO toDTO(){
		return new TheoryDTO(this.getKey(), this.getTitleLesson(), this.getContentLesson());
	}
	
	public void updateFromDTO(TheoryDTO lesson){
		this.setTitleLesson(lesson.getTitleLesson());
		this.setContentLesson(convertString2ArrayList(lesson.getContentLesson()));
	}
	
	public String getContentLesson() {
		String t = "";
		for(String i : this.contentLesson){
			t += i;
		}
		return t;
	}

	public void setContentLesson(ArrayList<String> content) {
		this.contentLesson = content;
	}

	public String getKey() {
		return key;
	}
	
	public ArrayList<String> convertString2ArrayList(String convert){
		ArrayList<String> result = new ArrayList<String>();
		int length = convert.length();
		int i = 0;
		do{
			length -= 450;
			if(length <= 0){
				result.add(convert.substring(i));
				return result;
			}
			String t = convert.substring(i, i + 449);
			result.add(t);
			i += 450;
		} while (length > 0);
		return result;
	}

	@Override
	public void jdoPreStore() {
		// TODO Auto-generated method stub
		
	}

	public void setTopicTheory(Topic topicTheory) {
		this.topicTheory = topicTheory;
	}

	public Topic getTopicTheory() {
		return topicTheory;
	}

	public void setTitleLesson(String titleTheory) {
		this.titleLesson = titleTheory;
	}

	public String getTitleLesson() {
		return titleLesson;
	}
}
